package p.ithorns.sample.module;


import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.util.UrlPathHelper;

/**
 * MultiModuleConfig
 *
 * @author ithorns
 * @version 1.0.0
 * @date 2021/10/26 15:02
 */
@Import({ModuleAnnotationRegistrar.class})
@Configuration
public class MultiModuleConfig implements WebMvcRegistrations {

    /**
     * 关于spring.mvc.pathmatch.matching-strategy的配置；PATH_PATTERN_MATCHER
     * ANT_PATH_MATCHER也可以, 官方文档上认为PathPattern语法更适合Web应用程序，并且其实现效率更高,
     * 参考
     * - {@link AbstractUrlHandlerMapping#initLookupPath},
     * - {@link UrlPathHelper#getLookupPathForRequest}
     * - {@link UrlPathHelper#skipServletPathDetermination}
     */
    @Override
    public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
        return new ModulePathHandlerMapping();
    }

    //    @Bean
//    public Map<String, ServletRegistrationBean<DispatcherServlet>> servletRegistrations(
//            WebApplicationContext context,
//            List<ModuleConfiguration> moduleConfigs
//    ) {
//        return moduleConfigs.stream().map(module -> createServletRegistrationBean(context, module))
//                .collect(Collectors.toMap(ServletRegistrationBean::getServletName, v -> v));
//    }
//
//    private ServletRegistrationBean<DispatcherServlet> createServletRegistrationBean(
//            WebApplicationContext context,
//            ModuleConfiguration module) {
//        DispatcherServlet servlet = new DispatcherServlet(context);
//        // 设置DispatcherServlet的上下文初始化参数，指向模块A的配置类
//        ServletRegistrationBean<DispatcherServlet> bean
//                = new ServletRegistrationBean<>(servlet, "/a/*");
//        bean.setName("ModuleA");
//        return bean;
//    }

//    @Bean
//    public ServletRegistrationBean<DispatcherServlet> aServlet() {
//        DispatcherServlet dispatcherServlet = new DispatcherServlet();
//
//        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
//        applicationContext.register(ModuleAConfig.class);
//        dispatcherServlet.setApplicationContext(applicationContext);
//
//        // 设置DispatcherServlet的上下文初始化参数，指向模块A的配置类
//        ServletRegistrationBean<DispatcherServlet> servletRegistrationBean
//                = new ServletRegistrationBean<>(dispatcherServlet, "/a/*");
//        servletRegistrationBean.setName("moduleA");
//        return servletRegistrationBean;
//    }

}